<?php

namespace app\api\logic;

use app\common\basic\BaseLogic;
use app\common\model\CrmFieldGroups;
use app\common\model\CrmFieldConfigs;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * CRM设置逻辑层
 * 用于处理客户资料分组和字段配置的业务逻辑
 */
class CrmSettingsLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new CrmFieldGroups();
    }

    /**
     * 根据ID获取字段
     * @param int $id
     * @return array|null
     */
    public function getFieldById(int $id)
    {
        try {
            $field = CrmFieldConfigs::with(['group'])->find($id);
            if ($field) {
                $data = $field->toArray();
                // 确保选项是数组格式
                if (!empty($data['options']) && is_string($data['options'])) {
                    $data['options'] = json_decode($data['options'], true);
                }
                return $data;
            }
            return null;
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return null;
        }
    }

    /**
     * 获取分组及其字段的树形结构
     * @return array
     */
    public function getGroupsWithFields(): array
    {
        try {
            $groups = CrmFieldGroups::order('sort asc, id asc')->field('id, name, code, icon, sort')->select();

            $result = [];
            foreach ($groups as $group) {
                $fields = CrmFieldConfigs::where('group_id', $group['id'])->field('id, group_id, name, placeholder, label, type, required, sort, max_length, validation, options, show_front_list, user_fill')->order('group_id asc, sort asc, id asc')->select();

                // 处理字段的选项数据
                foreach ($fields as &$field) {
                    if (!empty($field['options']) && is_string($field['options'])) {
                        $field['options'] = json_decode($field['options'], true);
                    }
                }
                $group['fields'] = $fields;
                $result[] = $group;
            }

            return $result;
        } catch (\Exception $e) {
            return [];
        }
    }

}